<template>
	<uv-upload
		:fileList="fileList1"
		name="1"
		multiple 
        :accept="accept"
        :uploadText="uploadText"
		:maxCount="maxCount"
		@afterRead="afterRead" 
		:previewFullImage="true"
		@delete="deletePic" 
	></uv-upload>
</template>
<script>
import { useCounterStore } from "../stores/counter";

	export default {

        props:{
            ddarr:{
                type: Array,
      // 数组的默认值可以是一个直接定义的数组
      default: () => []
            
            
            }
            ,
			maxCount:{
                type: Number,

      // 数组的默认值可以是一个直接定义的数组
      default: 1
            
            },
            accept:{
                type: String,

      // 数组的默认值可以是一个直接定义的数组
      default: 'image'
            
            },
            maxSize:{
                type: Number,

      // 数组的默认值可以是一个直接定义的数组
      default: 1000
            
            },
            uploadText:{
                type: String,

      // 数组的默认值可以是一个直接定义的数组
      default: '上传图片'
            
            },
        },
		data() {
			return {
				fileList1:[]
			}
		},
watch: {
	ddarr(){
	
	}
},
		created(){
		
	if(this.ddarr.length){

				console.log(this.ddarr);
				this.ddarr.forEach((item) => {
					this.fileList1.push({
						status: 'success',
						message: '上传成功',
						url: item
					})
				})
				

			}
		},
		methods: {


			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			
                this.$emit('updeteData',this[`fileList${event.name}`])
            },
			// 新增图片
			async afterRead(event) {


				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {


					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					const data =JSON.parse(result).data.url
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].
                    splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '上传成功',
						url: 'https://'+data[0]
					}))
					fileListLen++
					console.log(2222);
				}
console.log(this[`fileList${event.name}`]);
                this.$emit('updeteData',this[`fileList${event.name}`])

			},
			uploadFilePromise(url) {


				return new Promise((resolve, reject) => {
			const counter = useCounterStore()
					let a = uni.uploadFile({
						url: 'https://www.sanheiot1993.com/api/file/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header:{
							Authorization:counter.token
						},
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data)
							}, 1000)
						}
					});
				})
			}
		}
	}
</script>